package com.talent.service.iot.websocket.handler;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName：TlWsHandler
 * @Author: hszhou
 * @Date: 2024/12/6 13:17
 * @Description: 接收到websocket的消息
 */
public class TlWsHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final static Logger logger = LoggerFactory.getLogger(TlWsHandler.class);

    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        String text = msg.text();
        logger.info("接收到消息【{}】",text);
        Channel channel = ctx.channel();
        String longText = channel.id().asLongText();
        String shortText = channel.id().asShortText();
        logger.info("客户端的长ID=【{}】,短ID=【{}】",longText,shortText);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
        //初始化的时候 把节点信息带过来 然后将这个节点里面的数据+1

    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("注册");
        Channel channel = ctx.channel();
        String longText = channel.id().asLongText();
        String shortText = channel.id().asShortText();
        logger.info("客户端的长ID=【{}】,短ID=【{}】",longText,shortText);
        clients.add(channel);
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("注销");
        clients.add(ctx.channel());
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("激活");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("失效");
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        clients.add(ctx.channel());
        ctx.channel().close();
        super.exceptionCaught(ctx, cause);
    }
}
